package com.basker.pisces.core.operator.handler;

import java.text.MessageFormat;

import com.basker.pisces.core.operator.CompareOperator;
import com.basker.pisces.core.operator.ICompareOperatorHandler;

public class SqlCompareOperatorHandler implements ICompareOperatorHandler {

    public static final String HOST_VAR = "$host";

    /**
     * 获取Sql条件表达式
     *
     * @param fieldName 物理字段名
     * @param op        操作符号对象
     * @param value     条件值
     * @return 字段+符号+参数/条件值，如 "fieldName = ?"或者"fieldName = 1"
     */
    @Override
    public String getConditionExpression(String fieldName, CompareOperator op, Object value, boolean isParameterExp) {
        String valExp = this.getParameterExpression(fieldName, op, value, isParameterExp);
        return MessageFormat.format("{0}.{1} {2} {3}", HOST_VAR, fieldName, op.getName(), valExp);
    }

    @Override
    public Object updateValue(Object value) {
        return value;
    }

    /**
     * 拼接Sql表达式的参数表达式，通常返回?
     *
     * @param value
     * @param filteValue
     * @return ?
     */
    protected String getParameterExpression(String fieldName, CompareOperator op, Object value,
                                            boolean isParameterExp) {

        if (isParameterExp) {
            return "?";
        } else {
            String valExp = String.valueOf(value);
            if (value instanceof String) {
                valExp = "'" + valExp + "'";
            }

            return valExp;
        }
    }

}
